package prop;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/*
 * 
 */
public class PropertiesLoader {

  private static Properties properties = null;
  private static String defaultLocation = "/conf/default.properties";
  private static String localLocation = "/conf/local.properties";

  private PropertiesLoader() {
  };

  private static Properties loadProperties(String defaultFileName,
      String clientFilename) {
    Properties mergedProperties = new Properties();
    Properties defaultProperties = new Properties();
    Properties clientProperties = new Properties();
    InputStream in;
    try {
      in = ClassLoader.class.getResourceAsStream(defaultFileName);
      defaultProperties.load(in);
      in.close();
      in = ClassLoader.class.getResourceAsStream(clientFilename);
      clientProperties.load(in);
      in.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    mergedProperties.putAll(defaultProperties);
    mergedProperties.putAll(clientProperties);
    return mergedProperties;
  }

  public static final Properties recreate(String defaultLocation,
      String localLocation) {
    if (properties == null
        || !defaultLocation.equals(PropertiesLoader.defaultLocation)
        || !localLocation.equals(PropertiesLoader.localLocation)) {
      PropertiesLoader.defaultLocation = defaultLocation;
      PropertiesLoader.localLocation = localLocation;
      properties = loadProperties(defaultLocation, localLocation);
    }
    return properties;
  }

  public static final Properties getProperties() {
    return recreate(defaultLocation, localLocation);
  }

  public static int getIntValue(String s, int defaultValue) {
    String val = getProperties().getProperty(s);
    int res = defaultValue;
    try {
      res = Integer.parseInt(val);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return res;
  }

  public static double getDoubleValue(String s, double defaultValue) {
    String value = getProperties().getProperty(s);
    double result = defaultValue;
    try {
      result = Double.parseDouble(value);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    }
    return result;
  }

  public static String getStringValue(String someString, String defaultValue) {
    String value = getProperties().getProperty(someString);
    if (value == null) {
      value = defaultValue;
    }
    return value;
  }
}
